package com.wyman.factory.support;

import com.wyman.BeanException;
import com.wyman.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @Author 李伟民
 * @Description
 * @DateTime 2024/11/25 18:48
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy{

    //要同时处理 带参的和不带参的对象实例化
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeanException {

        Class<?> clazz = beanDefinition.getBeanClass();
        Object bean;
        try {
            //带参实例化
            if(args!=null&&ctor!=null){
                bean = clazz.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
            }
            //空参实例化
            else {
                bean = clazz.getDeclaredConstructor().newInstance();
            }

        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }

        return bean;
    }
}
